package com.learning.crpc.consummer;

import com.learning.crpc.Application;
import com.learning.crpc.annotation.CrpcReference;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.lang.reflect.Field;

/**
 * @program: diy_rpc
 * @description:
 * @author: CaoYong
 * @create: 2021-07-01 16:26
 **/
public class CrpcConsummerPostProcessor implements ApplicationContextAware, InstantiationAwareBeanPostProcessor {

    ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

//    @Override
//    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
//        Field[] declaredFields = bean.getClass().getDeclaredFields();
//        for (Field field: declaredFields) {
//            try {
//                if (!field.isAnnotationPresent(CrpcReference.class)) {
//                    continue;
//                }
//                CrpcReference crpcReference = field.getAnnotation(CrpcReference.class);
//                Object referenceBean = ProxyFactory.getProxy(new Class[]{field.getType()});
//                field.setAccessible(true);
//                field.set(bean, referenceBean);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
//        return false;
//    }

    @Override
    public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
        Field[] declaredFields = bean.getClass().getDeclaredFields();
        for (Field field: declaredFields) {
            try {
                if (!field.isAnnotationPresent(CrpcReference.class)) {
                    continue;
                }
                CrpcReference crpcReference = field.getAnnotation(CrpcReference.class);
                Object referenceBean = ProxyFactory.getProxy(new Class[]{field.getType()});
                field.setAccessible(true);
                field.set(bean, referenceBean);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return true;
    }
}
